package com.shengdou.as.slopsapptest.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.BitmapCallback;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.callback.StringCallback;
import com.shengdou.as.slopsapptest.Activity.LoginActivity;
import com.shengdou.as.slopsapptest.Activity.MainActivity;
import com.shengdou.as.slopsapptest.BuildConfig;
import com.shengdou.as.slopsapptest.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by AS on 2016/11/15.
 */

public class HttpUtils {
    public static LoadingDialog loadingdialog = null;
    private static Context contexts;
    public static String user_agent = OkHttpUtils.head("User-Agent").getHeaders().get("User-Agent");
    public static String key = "NzsefUbG40HfzIDF";
    public static String time;
    public static String sha;

    //判断网络连接
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            //如果仅仅是用来判断网络连接
            //则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo info = cm.getActiveNetworkInfo();
            /*if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }*/
            if (info == null || !cm.getBackgroundDataSetting()) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    //获取厂名,故障申报，版本更新
    public static void postFactory(final Handler mHandler, final String url, final Map<String, String> params, final int tag, Context context) {
        if (context != null) {
            contexts = context;
        }
        PostOkHttpFactory(url, params, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(tag, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
//                call.cancel();
                LogUtil.e("EEEEEEE", e.getMessage() + "");
//                ToastUtils.showToast("请求失败！");
            }
        });
    }

    //post请求数据有参数dialog
    public static void PostOkHttpFactory(String url, Map<String, String> params, final ResultBack callback) {
        time = DateUtils.getStringToDate() + "";
        LogUtil.e(user_agent + key + time);
        sha = SHA1.encryptToSHA(SHA1.encryptToSHA(user_agent + key) + time);
        LogUtil.e("加密的信息" + sha);
        OkHttpUtils
                .post(url).tag(url)
                .headers("user-key", sha)
                .headers("time", time)
                .params(params)
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            LogUtil.e("response+++++++++", s);
                            JSONObject jsonObject = new JSONObject(s);
                            int status = jsonObject.getInt("status");
                            if (status == 0) {
//                                ToastUtils.showToast(jsonObject.getString("status_text"));
                            } else if (status == 100) {
                                ToastUtils.showToast(jsonObject.getString("status_text"));
                                Intent intent = new Intent(contexts, LoginActivity.class);
                                contexts.startActivity(intent);
                                JPushInterface.deleteAlias(contexts, 0);
                                MainActivity.exit();
                            } else {
                                callback.onSuccess(s);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        LogUtil.e(response.toString());
                        callback.onFinished(call, e);
                    }
                });

    }

    //有参数的有dialog（报警记录信息，故障申报，故障列表，添加管理员）
    public static void post(final Handler mHandler, final String url, final Map<String, String> params, final int tag, Context context) {
        if (context != null) {
            contexts = context;
        }
        loadingdialog = new LoadingDialog(contexts);
        loadingdialog.builder();
        loadingdialog.setCancelable(false);
        loadingdialog.setBACKCancelable(true);
        loadingdialog.setMsg("正在加载...");
        if (loadingdialog.isShowing()) {
            loadingdialog.setdismiss();
        } else {
            loadingdialog.show();
        }
        PostOkHttps(url, params, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(tag, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
//                call.cancel();
                LogUtil.e("EEEEEEE", e.getMessage() + "");
//                ToastUtils.showToast("请求失败！");
            }
        });


    }

    //首次请求
    public static void postFirst(final Handler mHandler, final String url, final Map<String, String> params, final int tag, Context context) {
        if (context != null) {
            contexts = context;
        }
        loadingdialog = new LoadingDialog(contexts);
        loadingdialog.builder();
        loadingdialog.setCancelable(false);
        loadingdialog.setBACKCancelable(true);
        loadingdialog.setMsg("正在加载...");
        if (loadingdialog.isShowing()) {
            loadingdialog.setdismiss();
        } else {
            loadingdialog.show();
        }
        LogUtil.e("+++++++++" + params.get("mobile"), url);
        PostFirstOkHttps(url, params, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(tag, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
//                call.cancel();
                LogUtil.e("EEEEEEE", e.getMessage() + "");
//                ToastUtils.showToast("请求失败！");
            }
        });


    }

    //post首次请求数据
    public static void PostFirstOkHttps(String url, Map<String, String> params, final ResultBack callback) {
        OkHttpUtils
                .post(url).tag(url)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (loadingdialog != null) loadingdialog.setdismiss();
                        try {
                            LogUtil.e("response", s);
                            JSONObject jsonObject = new JSONObject(s);

                            int status = jsonObject.getInt("status");
                            if (status == 0) {
                                ToastUtils.showToast(jsonObject.getString("status_text"));
                            } else if (status == 100) {
                                ToastUtils.showToast(jsonObject.getString("text"));
                            } else {
                                callback.onSuccess(s);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (loadingdialog != null) loadingdialog.setdismiss();
                        callback.onFinished(call, e);
                    }
                });
    }

    //有参数的无dialogde(登录，版本更新，一周实时数据，24小时数据，单水池实时数据接口，检测仪冲洗)
    public static void postParmas(final Handler mHandler, final String url, final Map<String, String> params, final int tag, Context context) {
        if (context != null) {
            contexts = context;
        }

        PostOkHttps(url, params, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(tag, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
//                call.cancel();
                LogUtil.e("Exception", e.getMessage() + "");
//                ToastUtils.showToast("请求失败！");
            }
        });


    }

    //无参数的（厂名，报警记录）
    public static void post(final Handler mHandler, final String url, final int code, Context context) {
        if (context != null) {
            contexts = context;
        }

        loadingdialog = new LoadingDialog(contexts);
        loadingdialog.builder();
        loadingdialog.setCancelable(false);
        loadingdialog.setBACKCancelable(true);
        loadingdialog.setMsg("正在加载...");
        if (loadingdialog.isShowing()) {
            loadingdialog.setdismiss();
        } else {
            loadingdialog.show();
        }

        PostNoInfoOkHttps(url, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(code, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
                /*Intent intent = new Intent(contexts, LoginActivity.class);
                contexts.startActivity(intent);
                MainActivity.exit();*/
                LogUtil.e("Exception", e.getMessage() + "");
            }
        });


    }


    //无参数的没有dialog（获取水池名字）
    public static void postspool(final Handler mHandler, final String url, final int code, Context context) {
        if (context != null) {
            contexts = context;
        }

        loadingdialog = new LoadingDialog(contexts);
        loadingdialog.builder();
        loadingdialog.setCancelable(false);
        loadingdialog.setBACKCancelable(true);
        loadingdialog.setMsg("正在加载...");
        if (loadingdialog.isShowing()) {
            loadingdialog.setdismiss();
        } else {
            loadingdialog.show();
        }

        PostNoInfoOkHttpsPool(url, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(code, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
                /*Intent intent = new Intent(contexts, LoginActivity.class);
                contexts.startActivity(intent);
                MainActivity.exit();*/
                LogUtil.e("Exception", e.getMessage() + "");
            }
        });


    }

    //无参数的没有dialog（水池泥位高度，管理员列表）
    public static void posts(final Handler mHandler, final String url, final int tag, Context context) {
        if (context != null) {
            contexts = context;
        }

        PostNoInfoOkHttps(url, new ResultBack() {
            @Override
            public void onSuccess(String result) {
                msg(tag, result, mHandler);
            }

            @Override
            public void onFinished(Call call, Exception e) {
                call.cancel();
            }
        });


    }

    static String info = null;

    //无参数的
    public static void PostNoInfoOkHttpsPool(final String url, final ResultBack callback) {
        if (!SharedPreferenceUtil.getPreferenceString(contexts, "session_id").isEmpty()) {
            OkHttpUtils
                    .post(url).tag(url)
                    .params("session_id", SharedPreferenceUtil.getPreferenceString(contexts, "session_id"))
                    .execute(new StringCallback() {

                                 @Override
                                 public void onSuccess(String s, Call call, Response response) {
                                     if (loadingdialog != null) loadingdialog.setdismiss();
                                     try {
                                         LogUtil.e("response", s);
                                         JSONObject jsonObject = new JSONObject(s);
                                         int status = jsonObject.getInt("status");
                                         if (status == 0) {
                                             ToastUtils.showToast(jsonObject.getString("status_text"));
                                         } else if (status == 100) {
                                             info = status + "";//判断是否返回登陆
                                             ToastUtils.showToast(jsonObject.getString("text"));
                                             SharedPreferenceUtil.savePreferenceString(contexts, "session_id", null);
                                             Intent intent = new Intent(contexts, LoginActivity.class);
                                             contexts.startActivity(intent);
                                             JPushInterface.deleteAlias(contexts, 0);
                                             MainActivity.exit();
                                         } else {
                                             callback.onSuccess(s);
                                         }
                                     } catch (JSONException e) {
                                         e.printStackTrace();
                                     }
                                 }

                                 @Override
                                 public void onError(Call call, Response response, Exception e) {
                                     super.onError(call, response, e);
                                     if (loadingdialog != null) loadingdialog.setdismiss();
                                     callback.onFinished(call, e);
                                 }
                             }
                    );
        } else {
            OkHttpUtils
                    .post(url).tag(url)
                    .execute(new StringCallback() {

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            try {
                                LogUtil.e("response", s);
                                JSONObject jsonObject = new JSONObject(s);
                                int status = jsonObject.getInt("status");
                                if (status == 0) {
                                    ToastUtils.showToast(jsonObject.getString("status_text"));
                                } else if (status == 100) {
                                    info = status + "";//判断是否返回登陆
                                    ToastUtils.showToast(jsonObject.getString("text"));
                                    SharedPreferenceUtil.savePreferenceString(contexts, "session_id", null);
                                    Intent intent = new Intent(contexts, LoginActivity.class);
                                    contexts.startActivity(intent);
                                    MainActivity.exit();
                                } else {
                                    callback.onSuccess(s);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            callback.onFinished(call, e);
                        }
                    });
        }
    }

    //post请求数据有参数dialog
    public static void PostOkHttps(String url, Map<String, String> params, final ResultBack callback) {
        if (!SharedPreferenceUtil.getPreferenceString(contexts, "session_id").isEmpty()) {
            OkHttpUtils
                    .post(url).tag(url)
                    .params(params)
                    .params("session_id", SharedPreferenceUtil.getPreferenceString(contexts, "session_id"))
                    .execute(new StringCallback() {

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            try {
                                LogUtil.e("response+++++++++", s);
                                JSONObject jsonObject = new JSONObject(s);

                                int status = jsonObject.getInt("status");
                                if (status == 0) {
//                                ToastUtils.showToast(jsonObject.getString("status_text"));
                                } else if (status == 100) {
                                    ToastUtils.showToast(jsonObject.getString("status_text"));
                                    SharedPreferenceUtil.savePreferenceString(contexts, "session_id", null);
                                    Intent intent = new Intent(contexts, LoginActivity.class);
                                    contexts.startActivity(intent);
                                    JPushInterface.deleteAlias(contexts, 0);
                                    MainActivity.exit();
                                } else {
                                    callback.onSuccess(s);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            callback.onFinished(call, e);
                        }
                    });
        } else {
            LogUtil.e("session_id", "{}{}{}{}{}");
            OkHttpUtils
                    .post(url).tag(url)
                    .params(params)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            try {
                                LogUtil.e("responsesessionid空", s);
                                JSONObject jsonObject = new JSONObject(s);

                                int status = jsonObject.getInt("status");
                                if (status == 0) {
//                                ToastUtils.showToast(jsonObject.getString("status_text"));
                                } else if (status == 100) {
                                    ToastUtils.showToast(jsonObject.getString("status_text"));
                                    SharedPreferenceUtil.savePreferenceString(contexts, "session_id", null);
                                    Intent intent = new Intent(contexts, LoginActivity.class);
                                    contexts.startActivity(intent);
                                    JPushInterface.deleteAlias(contexts, 0);
                                    MainActivity.exit();
                                } else {
                                    callback.onSuccess(s);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            callback.onFinished(call, e);
                        }
                    });
        }
    }

    public static void msg(int tag, Object result, Handler handler) {
        Message message = Message.obtain();
        message.what = tag;
        message.obj = result;
        handler.sendMessage(message);
    }

    //无参数的
    public static void PostNoInfoOkHttps(String url, final ResultBack callback) {
        if (!SharedPreferenceUtil.getPreferenceString(contexts, "session_id").isEmpty()) {
            OkHttpUtils
                    .post(url).tag(url)
                    .params("session_id", SharedPreferenceUtil.getPreferenceString(contexts, "session_id"))
                    .execute(new StringCallback() {

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            try {
                                LogUtil.e("response", s);
                                JSONObject jsonObject = new JSONObject(s);
                                int status = jsonObject.getInt("status");
                                if (status == 0) {
                                    ToastUtils.showToast(jsonObject.getString("status_text"));
                                } else if (status == 100) {
                                    ToastUtils.showToast(jsonObject.getString("text"));
                                    SharedPreferenceUtil.savePreferenceString(contexts, "session_id", null);
                                    Intent intent = new Intent(contexts, LoginActivity.class);
                                    contexts.startActivity(intent);
                                    JPushInterface.deleteAlias(contexts, 0);
                                    MainActivity.exit();
                                } else {
                                    callback.onSuccess(s);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            callback.onFinished(call, e);
                        }
                    });
        } else {
            OkHttpUtils
                    .post(url).tag(url)
                    .execute(new StringCallback() {

                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            try {
                                LogUtil.e("response", s);
                                JSONObject jsonObject = new JSONObject(s);
                                int status = jsonObject.getInt("status");
                                if (status == 0) {
                                    ToastUtils.showToast(jsonObject.getString("status_text"));
                                } else if (status == 100) {
                                    ToastUtils.showToast(jsonObject.getString("text"));
                                    SharedPreferenceUtil.savePreferenceString(contexts, "session_id", null);
                                    Intent intent = new Intent(contexts, LoginActivity.class);
                                    contexts.startActivity(intent);
                                    JPushInterface.deleteAlias(contexts, 0);
                                    MainActivity.exit();
                                } else {
                                    callback.onSuccess(s);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            if (loadingdialog != null) loadingdialog.setdismiss();
                            callback.onFinished(call, e);
                        }
                    });
        }
    }

    public interface ResultBack {
        void onSuccess(String result);


        void onFinished(Call call, Exception e);
    }


    /**
     * 显示图片
     *
     * @param url
     */
    public static void mImageView(final Handler mHandler, String url, final int tag) {
        OkHttpUtils
                .get(url)//
                .params("session_id", SharedPreferenceUtil.getPreferenceString(contexts, "session_id"))
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Bitmap bitmap, Call call, Response response) {
                        msg(tag, bitmap, mHandler);
                    }
                });
    }


    /**
     * 下载文件
     *
     * @param url
     */
    public static void inProgress(final Context context, String url, String filesEnvironment) {
        final ProgressDialog dialog = new ProgressDialog(context);
        dialog.setTitle("正在下载");
        dialog.setCancelable(false);
        dialog.setIcon(R.mipmap.ic_logo);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.show();
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo == null) {
            ToastUtils.showToast("请检查网络环境");
        }

        OkHttpUtils.get(url)//
                .params("session_id", SharedPreferenceUtil.getPreferenceString(contexts, "session_id"))
                .execute(new FileCallback(filesEnvironment, "slopsApp.apk") {
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        LogUtil.e("fesddijdisjfdfji", response + "");
                        installApk(file, context);
                        dialog.dismiss();
                    }

                    @Override
                    public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        super.downloadProgress(currentSize, totalSize, progress, networkSpeed);
                        dialog.setProgress((int) (100 * progress));
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        ToastUtils.showToast("下载更新包失败");
                        dialog.dismiss();
                    }
                });
    }

    /**
     * 安装应用程序
     */
    private static void installApk(File response, Context context) {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setType("application/vnd.android.package-archive");
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", response);
            intent.setData(contentUri);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            //关键点：
            //安装完成后执行打开
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setDataAndType(Uri.fromFile(response),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 卸载应用程序
     */
    private static void uninstall(Context context) {
        Uri uri = Uri.parse("package:com.shengdou.application");
        Intent intent = new Intent(Intent.ACTION_DELETE, uri);
        context.startActivity(intent);
    }


}
